
//
//  HTEmoticonPageCell.swift
//  weibo
//
//  Created by JonsonLiu on 16/4/28.
//  Copyright © 2016年 liujonson. All rights reserved.
//

import UIKit

class HTEmoticonPageCell: UICollectionViewCell {
    
    
    //定义数组的属性
    var emtiocons : [HTEmoticon]? {
    
        didSet{
        
            guard let e = emtiocons else{
            
                return
            }
            
            
            for value in emoticonButtons {
            
                value.hidden = true
            }
            
            
            for (index , emtiocon) in e.enumerate(){
                let button = emoticonButtons[index]
                button.hidden = false
                
                button.emtcion = emtiocon
                
//                if emtiocon.type == "1" {
//                
//                    button.setTitle((emtiocon.code! as NSString).emoji(), forState: .Normal)
//                    
//                    button.setImage(nil, forState: .Normal)
//                }else{
//                
//                let image = UIImage(named: "\(emtiocon.folderName ?? "")/\(emtiocon.png ?? "")",inBundle:HTEmoticonKeyBoardViewModel.sharedViewModel.emotionBundle,compatibleWithTraitCollection : nil)
//                
//                button.setImage(image, forState: .Normal)
//                    button.setTitle(nil, forState: .Normal)
//                }
               
            }
        }
    }
    
    private lazy var deleteButton : UIButton = {
        let button = UIButton()
        
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: .Highlighted)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
        
        return button
    }()
    private lazy var emoticonButtons : [HMEmoticonPopButton] = []
    
    
    var indexPath : NSIndexPath? {
        didSet{
        
           // lable.text = "第\(indexPath?.section ?? 0)组, 第\(indexPath?.item ?? 0)页"
            messageLable.hidden = indexPath?.section != 0
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI(){
    
        //backgroundColor = RandomColor
        
//        addSubview(lable)
        contentView.addSubview(messageLable)
        
        messageLable.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-10)
        }
        
//        lable.snp_makeConstraints { (make) -> Void in
//            
//            make.center.equalTo(self)
//        }
        
        addChildButton()
        contentView.addSubview(deleteButton)
        
        let longPress = UILongPressGestureRecognizer(target: self, action: "longPress:")
        
        contentView.addGestureRecognizer(longPress)
    }
    
    
    @objc private func longPress(ges : UILongPressGestureRecognizer){
    
        let location = ges.locationInView(ges.view)
        
        func buttonWithLocation(location : CGPoint) -> HMEmoticonPopButton? {
        
            for value in emoticonButtons {
            
                if CGRectContainsPoint(value.frame, location){
                
                 return value
                }
            }
            
            return nil
        }
        
        
        guard let button = buttonWithLocation(location) else{
        
            popView.removeFromSuperview()
            
            return
        }
        
        
        switch ges.state {
        
        case .Began,.Changed :
            
            if popView.emotcionButton.emtcion == button.emtcion{
            
                return
            }
            
            
            let window = UIApplication.sharedApplication().windows.last!
            
            let rect = button.superview!.convertRect(button.frame, toView: window)
            
            popView.center.x = CGRectGetMidX(rect)
            popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
            
            popView.emotcionButton.emtcion = button.emtcion
            
            window.addSubview(popView)
            
          
        default :
            popView.removeFromSuperview()
            
            
        }
        
    }
    
    
    @objc private func deleteButtonClick(){
    
        NSNotificationCenter.defaultCenter().postNotificationName("HTEmoticonDeleteButtonClickNotification", object: nil)
    }
    
    
    private func addChildButton(){
    
        let  maxCount = HMEmoticonKetboardPageEmticonCount
        
        for _ in 0..<maxCount {
            let button = HMEmoticonPopButton()
            //button.backgroundColor = RandomColor
            
            button.addTarget(self, action: "emtcionButtonClick:", forControlEvents: .TouchUpInside)
            contentView.addSubview(button)
            
            emoticonButtons.append(button)
        }
    }
    
    
    
    @objc private func emtcionButtonClick(button : HMEmoticonPopButton)
    {
    
        
        NSNotificationCenter.defaultCenter().postNotificationName("HTEmoticonButtonClickNotification", object: nil , userInfo: ["emoticon":button.emtcion!])
        
        print(button.emtcion?.chs)
        
        let  window = UIApplication.sharedApplication().windows.last!
        
        let popView = HTEmoticonPopView.popView()
        
        let rect = button.superview!.convertRect(button.frame, toView: window)
        
        popView.center.x = CGRectGetMidX(rect)
        popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
        
        popView.emotcionButton.emtcion = button.emtcion
        
        window.addSubview(popView)
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            popView.removeFromSuperview()
        }
        
    
    }
    
    
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let  itemW = self.frame.width / CGFloat(HMEmoticonKetboardMaxCol)
        
        let  itemH = (self.frame.height - 25) / CGFloat(HMEmoticonKetboardMaxRow)
        
        for(index,value) in emoticonButtons.enumerate() {
        
            let col = index % HMEmoticonKetboardMaxCol
            let row = index / HMEmoticonKetboardMaxCol
            
            let x = CGFloat(col) * itemW
            let y = CGFloat(row) * itemH
            
            value.frame = CGRect(x: x, y: y, width: itemW, height: itemH)
        }
        
        
        //设置删除按钮
        let  deleteBUttonX = self.frame.width - itemW
        let deleteButtonY = self.frame.height - itemH - 25
        
        deleteButton.frame = CGRect(x: deleteBUttonX, y: deleteButtonY, width: itemW, height: itemH)
    }
    
    
    
    
    private lazy var popView : HTEmoticonPopView = {
        
        let popView = HTEmoticonPopView.popView()
        return popView
    }()
    
    private lazy var lable : UILabel = {
        
        let lable = UILabel()
        lable.textColor = UIColor.blackColor()
        lable.font = UIFont.systemFontOfSize(30)
        
        return lable
    }()
    
    private lazy var messageLable : UILabel = {
    
        let  labale = UILabel()
        
        labale.textColor = UIColor.grayColor()
        labale.font = UIFont.systemFontOfSize(12)
        labale.text = "最近使用的表情"
        return labale
    }()
}
